package com.cwd.arm.domain.repository.impl;

import com.cwd.arm.domain.entity.MonthAmountTotalEntity;
import com.cwd.arm.domain.entity.ProjectMonthAmountTotalEntity;
import com.cwd.arm.domain.repository.MonthAmountTotalRepository;
import com.cwd.arm.domain.repository.ProjectMonthAmountTotalRepository;
import com.cwd.arm.infrastructure.dao.ProjectMonthAmountTotalDao;
import com.cwd.arm.infrastructure.po.ProjectMonthAmountTotalPo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:项目每月统计
 * Created on 2021年11月16日
 *
 * @author yan
 */
@Repository
public class ProjectMonthAmountTotalRepositoryImpl implements ProjectMonthAmountTotalRepository {

    @Autowired
    private ProjectMonthAmountTotalDao dao;

    @Autowired
    private MonthAmountTotalRepository monthAmountTotalRepository;

    @Override
    public void save(List<ProjectMonthAmountTotalEntity> entityList) {
        List<MonthAmountTotalEntity> monthAmountTotalEntityList = new ArrayList<>();
        entityList.forEach(
                entity -> {
                    monthAmountTotalEntityList.add(monthAmountTotalRepository.buildEntity(entity));
                    ProjectMonthAmountTotalPo po = dao.selectOne(entity.getProjectId(), entity.getFyYear(), entity.getFyMonth());
                    if(po == null){
                        dao.save(convertToPo(entity));
                    }else{
                        ProjectMonthAmountTotalEntity poBuildEntity = buildEntity(po);
                        poBuildEntity.calculate(entity);
                        dao.updateById(convertToPo(poBuildEntity));
                    }
                }
        );
        monthAmountTotalRepository.save(monthAmountTotalEntityList);
    }

    private ProjectMonthAmountTotalPo convertToPo(ProjectMonthAmountTotalEntity entity) {
        ProjectMonthAmountTotalPo ProjectMonthAmountTotalPo = new ProjectMonthAmountTotalPo();
        BeanUtils.copyProperties(entity, ProjectMonthAmountTotalPo);
        return ProjectMonthAmountTotalPo;
    }

    private ProjectMonthAmountTotalEntity buildEntity(ProjectMonthAmountTotalPo po) {
        ProjectMonthAmountTotalEntity entity = new ProjectMonthAmountTotalEntity();
        BeanUtils.copyProperties(po, entity);
        return entity;
    }



}
